<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <!-- 进度条 -->
    <el-progress v-if="isShow" type="circle" :percentage="percentage" class="progress" />
  </el-upload>

</template>

<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDscBan12oNjxynUyd6OTL4dJk02rSowrY',
  SecretKey: 'VmptjMlyxiFYfdOxJRO9lANQHvL5e1DD'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      isShow: false,
      percentage: 0
    }
  },
  watch: {
    value() {
      this.imageUrl = this.value
    }
  },
  methods: {
    // 上传之前对文件的限制处理：格式、大小等
    beforeAvatarUpload(file) {
      const fileList = [
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/webp',
        'image/gif'
      ]
      const isType = fileList.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isType) {
        this.$message.error('上传头像图片只能是 jpeg jpg png webp gif格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isLt2M
    },
    // 自定义上传
    upload(obj) {
      // obj：上传的相关信息
      // obj.file 就是我们选择的文件
      console.log(obj)
      this.isShow = true
      cos.uploadFile({
        Bucket: 'zxj-34-1314536419', /* 填写自己的bucket，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: obj.file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: obj.file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.percentage = progressData.percent * 100
          // console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          this.imageUrl = `http://${data.Location}`
          this.$emit('input', this.imageUrl)
          this.isShow = false
          console.log('上传成功')
        }
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
